local status_ok, dap = pcall(require, "dap")
if not status_ok then
    vim.notify("nvim-dap not found!")
    return
end

local status_ok, dapui = pcall(require, "dapui")
if not status_ok then
    vim.notify("nvim-dap-ui not found!")
    return
end

local status_ok, dapvt = pcall(require, "nvim-dap-virtual-text")
if not status_ok then
    vim.notify("dap-virtual-text not found!")
    return
end

dapvt.setup({
    enabled = true,
    enable_commands = true,
    highlight_changed_variables = true,
    highlight_new_as_changed = false,
    show_stop_reason = true,
    commented = false,
    only_first_definition = true,
    all_references = false,
    filter_references_pattern = '<module',
    virt_text_pos = 'eol',
    all_frames = false,
    virt_lines = false,
    virt_text_win_col = nil
})

dapui.setup({
    force_buffers = false,
    icons = { expanded = "", collapsed = "" },
    elements_mappings = {
        scopes = {
            edit = "l",
            repl = "r",
        },
        watches = {
            edit = "l",
            repl = "r",
        },
        stacks = {
            open = "g",
        },
        breakpoints = {
            open = "g",
            toggle = "b",
        },
    },
    layouts = {
        {
            elements = {
                { id = "scopes", },
                { id = "stacks", },
                { id = "breakpoints", },
                { id = "watches", },
            },
            size = 80,
            position = "left",
        },
        {
            elements = {
                "repl",
                "console",
            },
            size = 0.25,
            position = "bottom",
        },
    },
    render = {
        max_value_lines = 3,
    },
    floating = {
        max_height = 0.5,
        max_width = 0.9,
        border = "rounded",
        mappings = {
            close = { 'q', '<Esc>' },
        },
    },
})

pcall(require("dap.ext.vscode").load_lauchjs)

local mappings = {
    ["<c-c>"] = dap.continue,
    ["<F10>"] = dap.step_over,
    ["<F11>"] = dap.step_into,
    ["<F12>"] = dap.step_out,
    ["<F9>"]  = dap.toggle_breakpoint,
    ["<c-t>"] = function()
        dapui.toggle({ reset = true })
    end,
    ["<c-k>"] = dapui.eval,
    ["<c-w>"] = dapui.elements.watches.add,
    ["<c-m>"] = dapui.float_element,
    ["<c-v>"] = function()
        dapui.float_element("scopes")
    end,
    ["<c-r>"] = function()
        dapui.float_element("repl")
    end,
    ["<c-q>"] = dap.terminate,
}
for keys, mapping in pairs(mappings) do
    vim.api.nvim_set_keymap("n", keys, "", { callback = mapping, noremap = true })
end
